const cloud = require('wx-server-sdk');
// 初始化 cloud
cloud.init({
    // API 调用都保持和云函数当前所在环境一致
    env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();
const _ = db.command;

modules.exports = function(collectionName, getMethodName) {
    return async(event, context) => {
        console.log(event);
        const response = {};
        const res = await cloud.callFunction({
            // 要调用的云函数名称
            name: getMethodName,
            data: event.query
        })
        if (res.result.body === null) {
            // 新建用户无该对象
            const { OPENID } = cloud.getWXContext();
            const data = Object.assign({}, event.data, { created_time: new Date, updated_time: new Date, owner: OPENID })
            await db.collection(collectionName)
                .add({
                    data
                })
                .then(() => {
                    response.code = 200;
                })
                .catch((err) => {
                    response.code = 500;
                    response.error = err;
                })
        } else {
            const id = res.result.body[0]._id;
            const data = Object.assign({}, event, { updated_time: new Date });
            Object.keys(data).forEach(key => {
                if (!data[key]) delete data[key];
            })
            try {
                await db.collection(collectionName)
                    .doc(id)
                    .update({
                        data
                    })
                response.code = 200;
            } catch (err) {
                response.error = err;
                response.code = 500;
            }
        }
        return response;
    }
}